package org.artifact.core.plugin.cmd;

import java.util.Scanner;

import org.artifact.core.enums.ServerStatusEnum;
import org.artifact.core.lang.IPlugin;
import org.artifact.core.lang.IServer;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;

public class CommandPlugin implements IPlugin {

	static Log log = LogFactory.get(CommandPlugin.class);
	
	private Thread thread = null;
	
	private static CommandPlugin ME = new CommandPlugin();
	
	private CommandConfig config;
	
	public static CommandPlugin me() {
		return ME;
	}
	
	public void setConfig(CommandConfig config) {
		this.config = config;
	}
	
	@Override
	public boolean start() {
		thread = new Thread(() ->  {
			Scanner sc = new Scanner(System.in);
			while (IServer.me().getStatus() != ServerStatusEnum.RUNNING) {
				try {
					Thread.sleep(1000L);
					log.info("Wait Server Start Finish");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			while (IServer.me().getStatus() == ServerStatusEnum.RUNNING) {
				System.out.print("cmd>");
				String cmd = null;
				try {
					cmd = sc.nextLine();
				} catch (Exception e) {
					break;
				}
				try {
					if (config == null) {
						System.out.println("not fond config ....");
					}else {
						config.execCommand(cmd);
					}
				} catch (Exception e) {
					e.printStackTrace();
					System.out.println("cmd error ....");
				}
			}
			sc.close();
		});
		thread.setDaemon(true);
		thread.start();
		return true;
	}

	@Override
	public boolean stop() {
		return true;
	}

}
